<?php

class dbConnect
{
	private $ip;
	private $account;
	private $password;
	private $dbname;
	private $mysqli;
	
	function setAddress($ip, $account, $password, $dbname=null)
	{
		$this->ip = $ip;
		$this->account = $account;
		$this->password = $password;
		$this->dbname = $dbname;
	}

	function setDbName($dbname)
	{
		$this->dbname = $dbname;
		$select_db = $this->mysqli->select_db($this->dbname);
		if (!$select_db)
		{
			die ("could not use ".$this->dbname.": ".mysqli_error($this->mysqli)."\n");
			return false;
		}
		return true;
	}

	function executeOnce($sql)
	{
		$ret = false;
		if($this->connectToDb())
		{
			$ret = $this->execute($sql);
			$this->mysqli->close();
		}
		return $ret;
	}

	function queryOnce($sql, $columnName=true)
	{
		$retArray = array();
		if($this->connectToDb())
		{
			$retArray = $this->query($sql, $columnName);
			$this->mysqli->close();
		}
		return $retArray;
	}
	
	function connectToDb()
	{
		$this->mysqli = @new mysqli($this->ip, $this->account, $this->password);
		if ($this->mysqli->connect_errno)
		{
			die('could not connect: '.mysqli_error($this->mysqli)."\n");
			return false;
		}
		if ($this->dbname != null) {
			$select_db = $this->mysqli->select_db($this->dbname);
			if (!$select_db)
			{
				die ("could not use ".$this->dbname.": ".mysqli_error($this->mysqli)."\n");
				return false;
			}
		}
		$this->mysqli->query("set names 'utf8';");//编码转化
		return true;
	}
	
	function execute($sql)
	{
		$db_result = $this->mysqli->query($sql);
		if(!$db_result)
		{
			echo "query sql error:".mysqli_error($this->mysqli)."\n";
		}
		return $db_result;
	}

	function query($sql, $columnName)
	{
		$db_result = $this->mysqli->query($sql);
		if(!$db_result)
		{
			echo "query sql error:".mysqli_error($this->mysqli)."\n";
			return null;
		}
		$ret = $db_result->fetch_all($columnName?MYSQLI_ASSOC:MYSQLI_NUM);
		$db_result->free();
		//print_r($ret);
		return $ret;
	}
	
	function close()
	{
		$this->mysqli->close();
	}
	
}

?>
